package oop.controller.action.sectstruct;

import oop.controller.action.DefaultAction;
import oop.data.SectionStructure;
import oop.data.TestStructure;
import oop.db.dao.SectionStructureDAO;

import com.mysql.jdbc.StringUtils;

public class EditAction extends DefaultAction {
	
	@Override
	public void performImpl() throws Exception {
		try {
			long sectionId = Long.parseLong(request.getParameter("sse_id"));
			SectionStructure sectionStructure = SectionStructureDAO.fetchById(sectionId)
					.get(0);
			request.setAttribute("section", sectionStructure);
			TestStructure testStructure = sectionStructure.getTestStructure();
			request.setAttribute("test", testStructure);
			title("Sửa phần " + sectionStructure.getOrder() + " trong cấu trúc đề " + testStructure.getName());

			String submit = request.getParameter("sse_submit");
			if (!StringUtils.isNullOrEmpty(submit)) {
				sectionStructure.setText(request.getParameter("sse_text"));
				sectionStructure.setOrder(Integer.parseInt(request
						.getParameter("sse_order")));

				SectionStructureDAO.shiftDown(testStructure.getId(),
						sectionStructure.getOrder());
				SectionStructureDAO.persist(sectionStructure);
				SectionStructureDAO.normalize(testStructure.getId());

				setNextAction("teststruct.view&tsv_id="
						+ testStructure.getId());
			}
		} catch (NumberFormatException ex) {
			request.setAttribute("message", "ID không hợp lệ");
			setNextAction("error");
		}
	}

}
